const path = require("path");
const fs = require("fs");
const iconv = require("iconv-lite");

// 配置

const BASE_DIR = path.join(`C:\\Users\\Administrator\\Desktop\\111`, "/心月狐727/data/Config/3442574732"); // 调整路径

// 递归查找所有 Default.save 文件
function findSaveFiles(dir, fileList = []) {
  const files = fs.readdirSync(dir);

  files.forEach((file) => {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);

    if (stat.isDirectory()) {
      findSaveFiles(filePath, fileList);
    } else if (file.endsWith("Default.save")) {
      const newPath = path.relative(BASE_DIR, filePath);
      const buffer = fs.readFileSync(filePath);

      const content = JSON.stringify(
        JSON.parse(iconv.decode(buffer, "gbk")),
        null,
        4
      );
      //
      const parentDir = path.join(dir);
      const parentFiles = fs.readdirSync(parentDir).find((item) => {
        return !item.includes(".");
      });

      fileList.push({
        name: file,
        path: newPath,
        fullPath: filePath,
        size: stat.size,
        mtime: stat.mtime,
        content,
        roleName: parentFiles,
      });
    }
  });

  return fileList;
}

exports.getConfig = (req, res) => {
  try {
    const files = findSaveFiles(BASE_DIR);
    res.json({ files, success: true });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

exports.saveConfig = (req, res) => {
  try {
    const { filePaths } = req.body;

    if (!Array.isArray(filePaths)) {
      return res.status(400).json({ error: "Invalid request data" });
    }

    const results = filePaths.map((item) => {
      try {
        const fullPath = path.join(BASE_DIR, item.path);
        const content = iconv.encode(item.content, "gbk");

        fs.writeFileSync(fullPath, content);
        return { path: item.path, success: true };
      } catch (err) {
        return { path: item.path, success: false, error: err.message };
      }
    });

    res.json({ results, success: true });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};
